# -*- coding: utf-8 -*-
import sys

sys.path.append('../..')
from common.config import *
from db.mysql import MysqlClient
from itertools import product
import requests, json
from common.helper import Helper


class Spider(object):
    def __init__(self):
        self.mysql = MysqlClient()
        self.name = "尊享e生2019版"

    def genProductInfo(self):
        plan = {
            # 年龄段
            "year": [str(i) for i in range(0, 61)],
            # 有无社保
            "socialSec": ["Y", "N"],
            # 保障期限
            "expire": ["1年"],
            # 交费方式
            "payType": ["年交"],
            # 质子重离子医疗
            "radiationMedical": ["0", "1000000"],
            # 恶性肿瘤医疗
            "cancerMedical": ["0", "1000000"],
            # 特殊疾病医疗
            "specialMedical": ["0", "6000000"],
            # 免赔
            "deductible": ["0", "1"]
        }

        for v in product(plan["year"], plan["socialSec"], plan["expire"], plan["payType"], plan["radiationMedical"],
                         plan["cancerMedical"], plan["specialMedical"], plan["deductible"]):
            data = Helper.formatProductInfo(plan, v)
            self.mysql.cursor.execute(domain[self.name]["insert_sql"].format(**data))
            self.mysql._conn.commit()
            print(domain[self.name]["insert_sql"].format(**data))

    # 执行爬虫
    def requestJson(self, dt=None, mysql=None):

        init_item = []
        if dt["radiationMedical"] != "0":
            init_item.append("1006001")
        if dt["cancerMedical"] != "0":
            init_item.append("1006003")
        if dt["specialMedical"] != "0":
            init_item.append("1006002")
        if dt["deductible"] != "0":
            init_item.append("1006004")

        data = {"bizNo": "INST190834380020", "productCode": "PRD190390008002", "packageCode": "PACK190350060017",
                "optionProjectIdList": init_item,
                "premiumFactorList": [{"productPremiumFactorId": 1014001, "value": "1", "unit": "年"},
                                      {"productPremiumFactorId": 1014002,
                                       "value": "" + str(2020 - int(dt["year"])) + "-01-01", "unit": ""},
                                      {"productPremiumFactorId": 1014003,
                                       "value": "无" if dt["socialSec"] == "N" else "有", "unit": ""}],
                "marketProductCode": "PRD190390008002"}
        payload = json.dumps(data)

        r = requests.post(url=domain[self.name]["url"], headers=domain[self.name]["header"], data=payload)
        if r.status_code == 200 and "请求成功" in r.text:
            price = Helper.decimalParse(r.json()["data"])
            data = {
                "name": self.name,
                "id": dt["id"],
                "price": price
            }
            print(data)
            mysql.updatePrice(data)
        else:
            data = {
                "name": self.name,
                "id": dt["id"],
                "state": 3
            }
            mysql.randTask(data)
            print("\n/*产品信息更新失败:%d*/" % dt["id"])
